package scjp.threads.guide;

public class AccountDanger implements Runnable {

    private Account account = new Account();

    public enum Days {MON, TUE, WED}

    ;

    public static void main(String args[]) {

        AccountDanger r = new AccountDanger();
        Thread one = new Thread(r);
        Thread two = new Thread(r);

        one.setName("Fred");
        two.setName("Lucy");


        Days.values();
        one.start();
        two.start();

    }

    @Override
    public void run() {

        for (int x = 0; x < 5; x++) {

            makeWithdraw(10);

            if (account.getBalance() < 0) {

                System.out.println("account is overdrawn");
            }
        }
    }

    private synchronized void makeWithdraw(int amount) {

        if (account.getBalance() >= amount) {
            System.out.println(Thread.currentThread().getName() + " is going to withdraw");

            try {
                Thread.sleep(10000);
            } catch (InterruptedException ignored) {
            }

            account.withDraw(amount);

            System.out.println(Thread.currentThread().getName() + " completes the withdrawl");

        } else {

            System.out.println("Not enough in account for " + Thread.currentThread().getName() + " to withdraw " + account.getBalance());

        }
    }
}
